//
//  UserInfoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/12.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UIColor+MethodExt.h"

#import "UserLeftViewController.h"
#import "UserCenterViewController.h"
#import "UserRightViewController.h"
#import "UserNet.h"
#import <UIImageView+WebCache.h>
#import "PrivateMsgSender.h"
#import "ChatViewController.h"
#import "UserDao.h"
#import "FriendNet.h"

#import "UIViewController+TextHUD.h"
#import <UIViewController+MBProgressHUD.h>

@interface UserInfoViewController ()

@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UIButton *addFriendButton;

@property (nonatomic, strong) UserLeftViewController *leftViewController;
@property (nonatomic, strong) UserCenterViewController *centerViewController;
@property (nonatomic, strong) UserRightViewController *righViewController;

@property (nonatomic, strong) UserModel *userInfo;
@property (nonatomic, assign) UInt64 userId;
@property (nonatomic, copy) NSString *userName;
@end

@implementation UserInfoViewController

- (instancetype)initWithUserId:(UInt64)userId userName:(NSString *)name
{
    if (self = [super init]) {
        self.userId = userId;
        self.userName = name;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self initTopView];
    
    [self changeToIndex:1];
    
    [self getUserInfo];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    
    self.navigationItem.title = self.userName;
    
    if ([[CurrentUser shareInstance] isMyFriend:self.userId]) {
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(0, 0, 28, 26);
        [rightButton setImage:[UIImage imageNamed:@"title_groupchats"] forState:UIControlStateNormal];
        [rightButton setImage:[UIImage imageNamed:@"title_groupchats_selection"] forState:UIControlStateHighlighted];
        [rightButton addTarget:self action:@selector(onChat:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightItem;
    }
}

- (void)initTopView
{
    self.topImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 190)];
    self.topImageView.userInteractionEnabled = YES;
    self.topImageView.image = [UIImage imageNamed:@"user_info_bg"];
    self.topImageView.backgroundColor = [UIColor clearColor];
    
    CGRect rect = CGRectMake(0, 20, 80, 80);
    self.headImageView = [[UIImageView alloc] initWithFrame:rect];
    self.headImageView.centerX = self.view.width/2;
    self.headImageView.layer.cornerRadius = rect.size.width/2;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.backgroundColor = [UIColor clearColor];
    [self.topImageView addSubview:self.headImageView];
    
    rect = self.headImageView.frame;
    rect.origin.y = self.headImageView.bottom + 15;
    rect.size.height = 25 ;
    
    if (![[CurrentUser shareInstance] isMyFriend:self.userId]) {
        self.addFriendButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.addFriendButton.frame = rect;
        self.addFriendButton.layer.cornerRadius = 5.0f;
        self.addFriendButton.backgroundColor = RGB(239.0f, 115.0f, 10.0f);
        [self.addFriendButton setTitle:@"加为好友" forState:UIControlStateNormal];
        [self.addFriendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.addFriendButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [self.topImageView addSubview:self.addFriendButton];
        
        [self.addFriendButton addTarget:self action:@selector(onClickedAddFriendButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, self.topImageView.height - 35, self.topImageView.width, 35)];
    [self.topImageView addSubview:barView];
    
    UIView *blackView = [[UIView alloc] initWithFrame:barView.bounds];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.alpha = 0.6f;
    [barView addSubview:blackView];
    
    CGFloat buttonWidth = barView.width / 3;
    UIButton *activityButton = [UIButton buttonWithType:UIButtonTypeCustom];
    activityButton.frame = CGRectMake(0, 0, buttonWidth, barView.height);
    activityButton.backgroundColor = [UIColor clearColor];
    [activityButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    activityButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [activityButton setTitle:@"活动" forState:UIControlStateNormal];
    [barView addSubview:activityButton];
    
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    infoButton.frame = CGRectMake(activityButton.right, 0, buttonWidth, barView.height);
    infoButton.backgroundColor = [UIColor clearColor];
    [infoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    infoButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [infoButton setTitle:@"资料" forState:UIControlStateNormal];
    [barView addSubview:infoButton];
    
    UIButton *photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    photoButton.frame = CGRectMake(infoButton.right, 0, buttonWidth, barView.height);
    photoButton.backgroundColor = [UIColor clearColor];
    [photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    photoButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [photoButton setTitle:@"相册" forState:UIControlStateNormal];
    [barView addSubview:photoButton];
    
    [activityButton addTarget:self action:@selector(onClickActivityButton:) forControlEvents:UIControlEventTouchUpInside];
    [infoButton addTarget:self action:@selector(onClickInfoButton:) forControlEvents:UIControlEventTouchUpInside];
    [photoButton addTarget:self action:@selector(onClickPhotoButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)onClickActivityButton:(id)sender
{
    [self changeToIndex:0];
}

- (void)onClickInfoButton:(id)sender
{
    [self changeToIndex:1];
}

- (void)onClickPhotoButton:(id)sender
{
    [self changeToIndex:2];
}

- (UserLeftViewController *)leftViewController
{
    if (!_leftViewController) {
        _leftViewController = [[UserLeftViewController alloc] init];
        _leftViewController.view.frame = CGRectMake(0, 0, self.view.width, self.view.height);
        [_leftViewController willMoveToParentViewController:self];
        [self addChildViewController:_leftViewController];
        [self.view addSubview:_leftViewController.view];
    }
    return _leftViewController;
}

- (UserCenterViewController *)centerViewController
{
    if (!_centerViewController) {
        _centerViewController = [[UserCenterViewController alloc] init];
        _centerViewController.view.frame = CGRectMake(0, 0, self.view.width, self.view.height);
        [_centerViewController willMoveToParentViewController:self];
        [self addChildViewController:_centerViewController];
        [self.view addSubview:_centerViewController.view];
    }
    return _centerViewController;
}

- (UserRightViewController *)righViewController
{
    if (!_righViewController) {
        _righViewController = [[UserRightViewController alloc] init];
        _righViewController.userId = self.userId;
        _righViewController.view.frame = CGRectMake(0, 0, self.view.width, self.view.height);
        [_righViewController willMoveToParentViewController:self];
        [self addChildViewController:_righViewController];
        [self.view addSubview:_righViewController.view];
    }
    return _righViewController;
}

- (void)getUserInfo
{
    @weakify(self);
    [UserNet queryUserWithUserId:self.userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dict = [responseObject objectForKey:@"data"];
            self.userInfo = [UserModel userWithDict:dict];
            self.userInfo.hobby_sport = nil;
            [self.centerViewController reloadWithUserInfo:self.userInfo];
            
            [[UserDao shareInstance] addOrUpdateUser:self.userInfo];
            
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.userInfo.icon] placeholderImage:[UIImage imageNamed:@"zc_photo_bg"]];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)changeToIndex:(NSInteger)index
{
    if (index == 0) {
        if (_righViewController) {
            [self.righViewController removeTopView];
        }
        
        if (_centerViewController) {
            [self.centerViewController removeTopView];
        }
        
        [self.leftViewController setTopView:self.topImageView];
        
        [self.view bringSubviewToFront:self.leftViewController.view];
        
    }else if (index == 1) {        
        [self.centerViewController setTopView:self.topImageView];
        
        [self.view bringSubviewToFront:self.centerViewController.view];
        
        if (_righViewController) {
            [self.righViewController removeTopView];
        }
    }else if (index == 2) {
        if (_centerViewController) {
            [self.centerViewController removeTopView];
        }
        
        [self.righViewController setTopView:self.topImageView];
        
        [self.view bringSubviewToFront:self.righViewController.view];
    }
}

#pragma mark - 加好友
- (void)onClickedAddFriendButton:(id)sender
{
    [self showHUD];
    [FriendNet applyAddFriendWithUserId:self.userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            [self showText:@"申请成功"];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [self hideHUD];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark - Test
- (void)onChat:(id)sender
{
    ChatViewController *chatViewController = [[ChatViewController alloc] init];
    chatViewController.msgSender = [[PrivateMsgSender alloc] initWithUser:self.userInfo];
    chatViewController.navigationItem.title = self.userInfo.name;
    [self.navigationController pushViewController:chatViewController animated:YES];
}

@end
